package cn.java79.quiz.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author oldliu
 * @since 1.0
 */
public class MybatisUtil {
    private static SqlSessionFactory factory;
    static {
        String resource = "mybatis-config.xml";
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
        factory= new SqlSessionFactoryBuilder().build(inputStream);
    }
    private MybatisUtil(){}
    public static SqlSession get(){
        return factory.openSession(false);
    }
    public static SqlSession get(boolean autoCommit){
        return factory.openSession(autoCommit);
    }
    public static void close(SqlSession s){
        if(s!=null){
            s.commit();
            s.close();
        }
    }
}
